package com.zch.starter.metrics.prometheus.springboot.starter.metrics;

import com.zch.starter.metrics.prometheus.springboot.starter.metrics.gauge.AbstractRegisterGauge;
import com.zch.starter.metrics.prometheus.springboot.starter.utils.TagsUtils;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.annotation.PostConstruct;
import java.util.Map;

public class RegisterGaugeServer implements ApplicationContextAware {
    private static ApplicationContext context;
    MeterRegistry meterRegistry;
    @PostConstruct
    public void init() {
     Map<String, AbstractRegisterGauge> map = context.getBeansOfType(AbstractRegisterGauge.class);
     if(map!=null&&map.size()>0){
         for(Map.Entry<String, AbstractRegisterGauge> entry:map.entrySet()){
             AbstractRegisterGauge gauge = entry.getValue();
             Gauge.builder(gauge.getMetricName(),gauge,AbstractRegisterGauge::execute)
                     .tags(TagsUtils.getTags(gauge.getCommonTagMap()))
                     .register(meterRegistry);
         }
     }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public void setMeterRegistry(MeterRegistry meterRegistry) {
        this.meterRegistry = meterRegistry;
    }
}
